package com.yhp.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.yhp.bean.Menu;
import com.yhp.bean.Role;
import com.yhp.dao.MiddleDao;
import com.yhp.dao.RoleDao;
import com.yhp.dao.impl.MiddleDaoImpl;
import com.yhp.dao.impl.RoleDaoImpl;
import com.yhp.service.RoleService;

public class RoleServiceImpl implements RoleService {
    private RoleDao roleDao = new RoleDaoImpl();
    private MiddleDao middleDao = new MiddleDaoImpl();

    @Override
    public List<Role> getRoleList(int pageIndex, int pageSize) {
        return roleDao.getRoleList(pageIndex, pageSize);
    }

    @Override
    public int total() {
        return roleDao.total();
    }

    @Override   //事务问题
    public int insertRole(String rolename, String state, String[] ids) {
        int k1 = 0;
        try {
            //1.新增角色表
            Role role = new Role();
            role.setRoleName(rolename);
            role.setRoleState(Integer.parseInt(state));
            int k = roleDao.insert(role);
            //2.新增中间表
            //如何获得新增数据的id?
            middleDao.insertMiddle(k, ids);
            k1 = 1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return k1;
    }

    @Override
    public Role findById(Integer roleId) {
        Role role = roleDao.findbyid(roleId);
        //需要对菜单进行分级
        List<Menu> menuList = role.getMenuList();
        //保存分级以后的菜单
        List<Menu> newMenuList = new ArrayList<>();
        for (Menu menu : menuList) {
            //说明是一级菜单
            if (menu.getUpmenuId() == 0) {
                List<Menu> secondList = new ArrayList<>();
                for (Menu second : menuList) {
                    if (second.getUpmenuId().equals(menu.getMenuId())) {
                        secondList.add(second);
                    }
                }
                menu.setSecondMenuList(secondList);
                newMenuList.add(menu);
            }
        }
        role.setMenuList(newMenuList);
        return role;
    }
}
